{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Chapter 7.5 Quantizing Models.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "metadata": {
        "id": "QcxNUJb99ONb",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 732
        },
        "outputId": "0079f6b4-a609-4efc-8a09-a392a709ac70"
      },
      "source": [
        "!pip install torch transformers"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Requirement already satisfied: torch in /usr/local/lib/python3.6/dist-packages (1.5.0+cu101)\n",
            "Collecting transformers\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/a3/78/92cedda05552398352ed9784908b834ee32a0bd071a9b32de287327370b7/transformers-2.8.0-py3-none-any.whl (563kB)\n",
            "\u001b[K     |████████████████████████████████| 573kB 2.9MB/s \n",
            "\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch) (1.18.3)\n",
            "Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from torch) (0.16.0)\n",
            "Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers) (3.0.12)\n",
            "Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers) (2.23.0)\n",
            "Collecting tokenizers==0.5.2\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/d1/3f/73c881ea4723e43c1e9acf317cf407fab3a278daab3a69c98dcac511c04f/tokenizers-0.5.2-cp36-cp36m-manylinux1_x86_64.whl (3.7MB)\n",
            "\u001b[K     |████████████████████████████████| 3.7MB 7.7MB/s \n",
            "\u001b[?25hRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers) (1.12.47)\n",
            "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers) (2019.12.20)\n",
            "Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers) (0.7)\n",
            "Collecting sentencepiece\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/98/2c/8df20f3ac6c22ac224fff307ebc102818206c53fc454ecd37d8ac2060df5/sentencepiece-0.1.86-cp36-cp36m-manylinux1_x86_64.whl (1.0MB)\n",
            "\u001b[K     |████████████████████████████████| 1.0MB 39.8MB/s \n",
            "\u001b[?25hRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers) (4.38.0)\n",
            "Collecting sacremoses\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/99/50/93509f906a40bffd7d175f97fd75ea328ad9bd91f48f59c4bd084c94a25e/sacremoses-0.0.41.tar.gz (883kB)\n",
            "\u001b[K     |████████████████████████████████| 890kB 49.0MB/s \n",
            "\u001b[?25hRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (3.0.4)\n",
            "Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2.9)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2020.4.5.1)\n",
            "Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (1.24.3)\n",
            "Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (0.9.5)\n",
            "Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (0.3.3)\n",
            "Requirement already satisfied: botocore<1.16.0,>=1.15.47 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (1.15.47)\n",
            "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (1.12.0)\n",
            "Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (7.1.2)\n",
            "Requirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (0.14.1)\n",
            "Requirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.47->boto3->transformers) (0.15.2)\n",
            "Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.47->boto3->transformers) (2.8.1)\n",
            "Building wheels for collected packages: sacremoses\n",
            "  Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for sacremoses: filename=sacremoses-0.0.41-cp36-none-any.whl size=893334 sha256=062da831c0e422df7a7afa4a701e74f06f882b89665793b94d9daf343ed538d7\n",
            "  Stored in directory: /root/.cache/pip/wheels/22/5a/d4/b020a81249de7dc63758a34222feaa668dbe8ebfe9170cc9b1\n",
            "Successfully built sacremoses\n",
            "Installing collected packages: tokenizers, sentencepiece, sacremoses, transformers\n",
            "Successfully installed sacremoses-0.0.41 sentencepiece-0.1.86 tokenizers-0.5.2 transformers-2.8.0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DjIYt4QS9YWL",
        "colab_type": "text"
      },
      "source": [
        ""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L0kxCNnI9RVc",
        "colab_type": "text"
      },
      "source": [
        "# Big Models Hate This One Weird Trick! (Quantization, T5, & PyTorch 1.4)\n",
        "\n",
        "As we know, models can be big lumbering beasts, comprised of millions of parameters (both weights and activations) that require lots of matrix multiplications to take an input and arrive at an answer. And for most of our work so far, that's been fine! We have mighty GPUs that can handle these burdens with ease.\n",
        "\n",
        "But what if we didn’t? We often package a model up for production inference usage so that it only runs on the CPU. And what if we wanted to run our model on a smaller embedded platform? Suddenly, both the size of the model and all those floating-point operations become a little more problematic. Thankfully, there’s a trick we can perform that makes our model smaller _and_ faster, normally with the trade off with some accuracy. Even better, PyTorch allows us to perform this one weird trick with just one line of code, with some other approaches for squeezing even more performance. Let’s have a quick look at _quantization_.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SyNq8LN_9idf",
        "colab_type": "text"
      },
      "source": [
        "## Quantization\n",
        "\n",
        "Every parameter in our model is a 32-bit floating point number, taking up 4 bytes of memory. That’s not a lot, but it can soon add up. Let's have a look at Google’s recent T5 transformer-based model, which has a `t5-small` variant that’s available in the `transformers` library. \n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yDxF0i309uJy",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "f47acad5-c8d7-4fc7-d0cf-a2cee9a536a2"
      },
      "source": [
        "import torch\n",
        "from transformers import pipeline, T5ForConditionalGeneration\n",
        "\t\t\n",
        "def count_parameters(model):\n",
        "  return sum(p.numel() for p in model.parameters())\n",
        "\t    \n",
        "base_model = T5ForConditionalGeneration.from_pretrained(\"t5-small\")\n",
        "\n",
        "param_count = count_parameters(base_model)\n",
        "\n",
        "memory = (param_count * 4) / (1024 *1024)\n",
        "memory\n"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "230.8154296875"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 16
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xzzcwPQW-NW_",
        "colab_type": "text"
      },
      "source": [
        "Even with the smallest pre-trained T5 weights, our model is roughly 60m parameters and weighs in at a whopping 230Mb! "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vY079U2m-Wh2",
        "colab_type": "text"
      },
      "source": [
        "However, what if we decided that we didn’t need the full precision of our floating-point parameters? If our parameters could be restricted to within a certain range of values, then we could use a smaller type of number representation to store the parameters. This _quantization_ is the key to speeding up our inference time and reducing the memory footprint of our models. What we tend to aim for is to quantize down from a 32-bit floating point to an 8-bit integer. The basic idea is:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jRM0VuTr-Y0k",
        "colab_type": "text"
      },
      "source": [
        "\n",
        "$x_{int8} = (\\frac{x_{float32}}{x_{scale}} + x_{offset})$\n",
        "\n",
        "Which is essentially just fitting the potential values of the parameters of a network to a line of $y = mx + c$, although due to the reduced resolution of the 8-bit integer, there's only so many values a parameter now may take instead of the huge amount that a `float32` value could be. PyTorch does its quantizing in a slightly more complicated affair that ensures that zero is always zero, but the basic idea is the same - we have a range of values that our parameters can take, and then find an appropriate pair $x_{scale}$ and $x_{offset}$ to provide 256 graduations to represent that range - or 255 if you think about PyTorch always keeping zero around."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yUJNQivcAVVZ",
        "colab_type": "text"
      },
      "source": [
        "At the moment (PyTorch 1.5), quantized layers are best supported with `CNN` and `Linear` layers. Thankfully, if we have a look at the model structure of T5, we can see a happy coincidence:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "heo9StPOAZEL",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "4855ce94-7df0-473f-f1ec-b352925f3580"
      },
      "source": [
        "base_model"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "T5Model(\n",
              "  (shared): Embedding(32128, 512)\n",
              "  (encoder): T5Stack(\n",
              "    (embed_tokens): Embedding(32128, 512)\n",
              "    (block): ModuleList(\n",
              "      (0): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (relative_attention_bias): Embedding(32, 8)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (1): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (2): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (3): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (4): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (5): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "    )\n",
              "    (final_layer_norm): T5LayerNorm()\n",
              "    (dropout): Dropout(p=0.1, inplace=False)\n",
              "  )\n",
              "  (decoder): T5Stack(\n",
              "    (embed_tokens): Embedding(32128, 512)\n",
              "    (block): ModuleList(\n",
              "      (0): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (relative_attention_bias): Embedding(32, 8)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (relative_attention_bias): Embedding(32, 8)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (1): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (2): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (3): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (4): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "      (5): T5Block(\n",
              "        (layer): ModuleList(\n",
              "          (0): T5LayerSelfAttention(\n",
              "            (SelfAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (1): T5LayerCrossAttention(\n",
              "            (EncDecAttention): T5Attention(\n",
              "              (q): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (k): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (v): Linear(in_features=512, out_features=512, bias=False)\n",
              "              (o): Linear(in_features=512, out_features=512, bias=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "          (2): T5LayerFF(\n",
              "            (DenseReluDense): T5DenseReluDense(\n",
              "              (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
              "              (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
              "              (dropout): Dropout(p=0.1, inplace=False)\n",
              "            )\n",
              "            (layer_norm): T5LayerNorm()\n",
              "            (dropout): Dropout(p=0.1, inplace=False)\n",
              "          )\n",
              "        )\n",
              "      )\n",
              "    )\n",
              "    (final_layer_norm): T5LayerNorm()\n",
              "    (dropout): Dropout(p=0.1, inplace=False)\n",
              "  )\n",
              ")"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HGSvW-kkAfyS",
        "colab_type": "text"
      },
      "source": [
        "Yes, that’s right, look at all those `Linear` layers! We should be able to get some benefit out of quantizing this model. "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qYznffbOAuSl",
        "colab_type": "text"
      },
      "source": [
        "## One Weird Trick — Dynamic Quantization\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "U8YLMB4KAvKL",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import torch.quantization\n",
        "\t\n",
        "quantized_model = torch.quantization.quantize_dynamic(base_model, {torch.nn.Linear}, dtype=torch.qint8)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I0DEsvrmA5kp",
        "colab_type": "text"
      },
      "source": [
        "No, really, that’s it. Chapter done. Bye!\n",
        "\n",
        "Oh, okay, if you really insist. But honestly, there’s not much more to it. Okay, firstly, a caveat in that `quantize_dynamic` will only quantize the weights, not the activations in our parameters. But all we need to do is pass in the `model` we wish to quantize and a dict of layers that we wish to replace with our quantized versions, in this case `Linear`. The function returns a new model, though you could run with the optional parameter `inplace=True` to mutate the original model rather than make a copy. \n",
        "\n",
        "Let’s save the model and take a look at the quantized size:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-8t9Hq62A9Sm",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 52
        },
        "outputId": "e2abd9b4-2dce-437a-e530-f53dc6e83938"
      },
      "source": [
        "!mkdir t5\n",
        "quantized_model.save_pretrained(\"t5\")\n",
        "!du -m t5"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "mkdir: cannot create directory ‘t5’: File exists\n",
            "121\tt5\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "l4AwvS1CBXzN",
        "colab_type": "text"
      },
      "source": [
        "Almost a 50% reduction in size! We can’t get down to 4 times smaller due to not being able to store the activations as 8-bit integers, but we’ve done pretty well for one line of code. Let's do a very simple microbenchmark using both models in the `transformers` library summarization pipeline. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-EydnHY3BbwT",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "base_summarizer = pipeline(\"summarization\", model=base_model, tokenizer=\"t5-small\")\n",
        "quantized_summarizer = pipeline(\"summarization\", model=quantized_model, tokenizer=\"t5-small\")"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BHhiTSOlBg-f",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "ee37076a-777e-4af2-ef18-da7048ece96b"
      },
      "source": [
        "%timeit base_summarizer(\"From the very beginning, Regan was seen as having series potential. After the television film scored highly in the ratings, work began on the development of the series proper. Ian Kennedy Martin's idea was for the series to be mainly studio-based, with more dialogue and less action, but producer Ted Childs disagreed, and in consequence Ian Kennedy Martin parted company with the project. Childs produced it on 16mm film, a format that allowed for a much smaller film unit than videotape at that time. This made it possible to shoot almost entirely on location which helped give the series a startling degree of realism and to use film editing techniques which enabled him to give the show a heavy bias toward action sequences. The television play and the subsequent series were commissioned by Thames Television and produced by its film division Euston Films. It was originally broadcast on ITV between 2 January 1975 and 28 December 1978 at 21:00–22:00 on weekdays (usually Mondays), with repeated screenings at the same time until the early 1980s. The writers were given strict guidelines to follow: \\\"Each show will have an overall screen time (minus titles) of 48 minutes 40 seconds. Each film will open with a teaser of up to 3 minutes, which will be followed by the opening titles. The story will be played across three acts, each being no more than 19 minutes and no less than 8 minutes in length. Regan will appear in every episode, Carter in approximately 10 out of 13 episodes. In addition to these main characters, scripts should be based around three major speaking parts, with up to ten minor speaking parts\")"
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "1 loop, best of 3: 29.4 s per loop\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-am4cPghCdtc",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "6e0b1484-ffe2-4523-85da-e4d00884a74e"
      },
      "source": [
        "%timeit quantized_summarizer(\"From the very beginning, Regan was seen as having series potential. After the television film scored highly in the ratings, work began on the development of the series proper. Ian Kennedy Martin's idea was for the series to be mainly studio-based, with more dialogue and less action, but producer Ted Childs disagreed, and in consequence Ian Kennedy Martin parted company with the project. Childs produced it on 16mm film, a format that allowed for a much smaller film unit than videotape at that time. This made it possible to shoot almost entirely on location which helped give the series a startling degree of realism and to use film editing techniques which enabled him to give the show a heavy bias toward action sequences. The television play and the subsequent series were commissioned by Thames Television and produced by its film division Euston Films. It was originally broadcast on ITV between 2 January 1975 and 28 December 1978 at 21:00–22:00 on weekdays (usually Mondays), with repeated screenings at the same time until the early 1980s. The writers were given strict guidelines to follow: \\\"Each show will have an overall screen time (minus titles) of 48 minutes 40 seconds. Each film will open with a teaser of up to 3 minutes, which will be followed by the opening titles. The story will be played across three acts, each being no more than 19 minutes and no less than 8 minutes in length. Regan will appear in every episode, Carter in approximately 10 out of 13 episodes. In addition to these main characters, scripts should be based around three major speaking parts, with up to ten minor speaking parts\")"
      ],
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "1 loop, best of 3: 16.6 s per loop\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oANUgOHTEDb0",
        "colab_type": "text"
      },
      "source": [
        "In addition to almost being half the size, the quantized model is almost twice as fast! So…why don’t we do this _all_ the time? Are there no downsides? Well…it depends. We **are** losing information in our inference in a quantized model as our values cannot map to all the possible floating-point values that we find in the original model. So the chain of multiplications will be less accurate in our quantized model than in the original. You’ll need to check the new model against a reference dataset to determine the accuracy loss and whether that loss is an acceptable trade-off compared to the reduced storage demands and faster execution."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w4IgTYAAEiI2",
        "colab_type": "text"
      },
      "source": [
        "## Other Quantizing Options Are Available"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "StgyLod9EtEl",
        "colab_type": "text"
      },
      "source": [
        "In addition to dynamic quantizing, PyTorch also offers _static quantizing_, where a trained model is modified to include _observer_ modules and a selection of data is fed into the model. During the inference on this data, the observers can generate a quantized distribution that fits best to the observed data and the activations that result. This can can produce even further space and time savings, especially with vision models like ResNet.\n",
        "\n",
        "However, for the best-in-class of accuracy in your smaller model, you'll want to investigate quantization-aware training (QAT). In this approach, the model fakes quantizing during the training loop of both the forward and backward passes; while all the computations take place with standard floats, everything is rounded down to integer values, so you end up with a quantized model after training is finished, but one with a higher accuracy than you can acheive with the dynamic or static approaches. "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0ufUnEbPHoNs",
        "colab_type": "text"
      },
      "source": [
        "## Is It Worth It?\n",
        "\n",
        "You might be wondering if you're just better off training a smaller model rather than going to all this effort to compress larger models. In the recent paper, [Train Large, Then Compress](https://arxiv.org/abs/2002.11794), there's a good deal of evidence presented that transformer-based models really do benefit from this approach. Because larger models converge faster than smaller ones, you will likely get more accurate results by training a large model and compressing than if you spent the same compute time on a smaller model. So go forth and compress!\n",
        "\n",
        "(and we'll see you back here in the future for _pruning_ models)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6NbH-K1IHkEC",
        "colab_type": "text"
      },
      "source": [
        "## Further Reading\n",
        "\n",
        "https://pytorch.org/docs/stable/quantization.html\n",
        "\n",
        "https://arxiv.org/abs/2002.11794"
      ]
    }
  ]
}